package org.ponly.cta4j.drawing.filter;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;

/**
 * 基于 jdk {@link ImageFilter} 实现的滤镜, 通过 jdk {@link ImageFilter} 来实现滤镜功能.
 *
 * @author vacoor
 * @since 1.0
 */
public class ImageFilterFilter implements Filter {
    private ImageFilter[] filters;

    /**
     * 创建一个空操作的滤镜实例.
     */
    public ImageFilterFilter() {
        this(new ImageFilter[0]);
    }

    /**
     * 创建一个使用给定滤镜过滤的滤镜实例.
     *
     * @param filters jdk image 滤镜
     */
    public ImageFilterFilter(final ImageFilter[] filters) {
        this.filters = filters.clone();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public BufferedImage apply(final BufferedImage image) {
        if (null == filters || 1 > filters.length) {
            return image;
        }

        /*
        final ImageProducer producer = image.getSource();
        for (ImageFilter filter : filters) {
            producer = new FilteredImageSource(producer, filter);
        }
        Image filtered = Toolkit.getDefaultToolkit().createImage(producer);
        if (filtered instanceof BufferedImage) {
            return (BufferedImage) filtered;
        }

        BufferedImage clone = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
        Graphics2D g2d = clone.createGraphics();
        g2d.drawImage(filtered, 0, 0, null);
        g2d.dispose();
        */
        final BufferedImage clone = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
        final Graphics2D g2d = clone.createGraphics();
        final Toolkit toolkit = Toolkit.getDefaultToolkit();

        g2d.drawImage(image, 0, 0, null);

        FilteredImageSource filtered;
        for (final ImageFilter filter : filters) {
            filtered = new FilteredImageSource(clone.getSource(), filter);

            final Image img = toolkit.createImage(filtered);
            g2d.drawImage(img, 0, 0, null);
        }

        g2d.dispose();

        return clone;
    }
}
